import { getOpenId, getUserProfile } from '../api/login';

export const requestOpenId = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      success: res => {
        if (res.code) {
          getOpenId({
            code: res.code,
          })
            .then(data => {
              console.log('*****openId&session_key******: ', data);
              uni.setStorageSync('openId', data.openid || '');
              uni.setStorageSync('session_key', data.session_key || '');
              resolve(data);
            })
            .catch(err => {
              reject(err);
            });
        }
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

export const getLoginStatus = () => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token');
    if (token) {
      getUserProfile()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    } else {
      resolve(false);
    }
  });
};
